import { fetchStoredToken, removeStoredToken } from "./token";
const appInstance = getApp();
function httpRequest(options) {
  const token = fetchStoredToken();
  if (token) {
    options.header = {
      ...options.header,
      Authorization: `Bearer ${token}`,
    };
  }
  return new Promise((resolve, reject) => {
    wx.request({
      ...options,
      url: `${appInstance.globalData.baseURL}${options.url}`,
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data);
        } else if (res.statusCode === 401) {
          removeStoredToken();
          wx.showModal({
            title: "认证失败",
            content: "请先登录",
            showCancel: false,
            success() {
              wx.navigateTo({
                url: "/pages/profile/profile",
              });
            },
          });
        } else {
          reject(new Error(`Request failed with status ${res.statusCode}`));
        }
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
}
export function get(url, options = {}) {
  return httpRequest({
    url,
    ...options,
  });
}
export function post(url, options = {}) {
  return httpRequest({
    url,
    method: "POST",
    ...options,
  });
}
export default httpRequest;
